package day11.reflect2;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import org.junit.Test;

public class Demo3 {
	@Test
	public void test() {
		Class<?> class1 = Student.class;
		//获取所有的public的构造器
		Constructor<?>[] cs = class1.getConstructors();
		//打印构造器个数
		System.out.println(cs.length);
		
		//循环
		for (Constructor<?> c : cs) {
			System.out.println(c);
		}
	}
	
	//获取所有的构造器
	@Test
	public void test2() {
		Class<?> class1 = Student.class;
		Constructor<?>[] cs = class1.getDeclaredConstructors();
		System.out.println("所有的构造器:" + cs.length);
		//循环
		for (Constructor<?> c : cs) {
			System.out.println(c);
		}
	}
	
	//获取私有的构造器
	@Test
	public void test3() throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		Class<?> class1 = Student.class;
		Constructor<?> private_c = class1.getDeclaredConstructor(String.class,String.class);
		System.out.println(private_c);
		
		//暴力反射
		private_c.setAccessible(true);
		
		Object obj = private_c.newInstance("admin","男");
	}
	
	//获取私有的构造器
	@Test
	public void test4() throws NoSuchMethodException, SecurityException {
		Class<?> class1 = Student.class;
		Constructor<?> default_c = class1.getDeclaredConstructor(String.class);
		System.out.println(default_c);
	}
	
	//获得protected构造器    实例化  public三个形参的构造器实例化
	@Test
	public void test5() throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		Class<?> class1 = Student.class;
		Constructor<?> protected_c = class1.getDeclaredConstructor(String.class,int.class);
		System.out.println(protected_c);
		
		//创建对象
		Student s = (Student)protected_c.newInstance("admin",23);
		System.out.println(s);
	}
	
	@Test
	public void test6() throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		Class<?> class1 = Student.class;
		Constructor<?> public_c = class1.getDeclaredConstructor(String.class,String.class,int.class);
		System.out.println(public_c);
		
		//创建对象
		Student s = (Student)public_c.newInstance("admin","男",23);
		System.out.println(s);
	}
}
